<script setup>
import { ref, onMounted, onActivated } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import StatusTag from '@/components/common/StatusTag.vue'
import ApprovalTimeline from '@/components/leave/ApprovalTimeline.vue'
import FloatingBackButton from '@/components/common/FloatingBackButton.vue'
import LogoutButton from '@/components/common/LogoutButton.vue'
import { getStudentLeaveDetail, cancelStudentLeave, getAdminLeaveDetail } from '@/api'

const route = useRoute()
const router = useRouter()
const auth = useAuthStore()
const id = route.params.id

const loading = ref(false)
const detail = ref(null)
const steps = ref([])

// 获取请假详情
const fetchDetail = async () => {
  loading.value = true
  try {
    // 根据角色选择合适的 API
    const response = auth.isAdmin ? await getAdminLeaveDetail(id) : await getStudentLeaveDetail(id)
    if (response.code === 0 && response.data) {
      const data = response.data
      detail.value = {
        typeLabel: data.type === 'sick' ? '病假' : data.type === 'personal' ? '事假' : '其他',
        timeRange: `${formatDateTime(data.start_at)} ~ ${formatDateTime(data.end_at)}`,
        hours: data.hours,
        status: data.status,
        reason: data.reason,
        attachment: data.attachment_url ? '已上传附件' : '无附件',
      }

      // 转换审批步骤
      steps.value = (data.steps || []).map((step) => ({
        title: step.title,
        time: step.acted_at ? formatDateTime(step.acted_at) : '—',
        comment: step.comment || '待处理',
        status: step.status,
      }))
    }
  } catch (error) {
    console.error('获取详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 格式化时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `2025-${month}-${day} ${hours}:${minutes}`
}

// 撤销请假
const handleCancel = async () => {
  if (!confirm('确定要撤销这条请假申请吗？')) return

  try {
    const response = await cancelStudentLeave(id)
    if (response.code === 0) {
      alert('✅ 撤销成功！')
      router.replace('/student/leave/list')
    } else {
      alert('❌ ' + (response.message || '撤销失败'))
    }
  } catch (error) {
    console.error('撤销失败:', error)
    alert('❌ ' + (error.message || '撤销失败'))
  }
}

onMounted(() => {
  fetchDetail()
})

// 每次页面激活时刷新数据
onActivated(() => {
  fetchDetail()
})
</script>

<template>
  <div class="page">
    <div class="container">
      <div class="header">
        <h2>请假详情</h2>
      </div>

      <div v-if="loading" class="loading-text">加载中...</div>
      <template v-else-if="detail">
        <div class="grid">
          <div class="card elevated">
            <div class="row">
              <div><strong>类型：</strong>{{ detail.typeLabel }}</div>
              <StatusTag :status="detail.status" />
            </div>
            <div class="kv">
              <span>时间段</span><b>{{ detail.timeRange }}</b>
            </div>
            <div class="kv">
              <span>时长(小时)</span><b>{{ detail.hours }}</b>
            </div>
            <div class="kv">
              <span>事由</span><b>{{ detail.reason }}</b>
            </div>
            <div class="kv">
              <span>附件</span><b>{{ detail.attachment }}</b>
            </div>
          </div>

          <div class="card elevated">
            <h3 class="section-title">审批进度</h3>
            <ApprovalTimeline :steps="steps" />
          </div>
        </div>

        <div v-if="detail.status === 'pending'" class="actions">
          <button class="btn danger" @click="handleCancel">撤销申请</button>
        </div>
      </template>
      <div v-else class="error-text">加载失败</div>
    </div>
    <FloatingBackButton />
    <LogoutButton />
  </div>
</template>

<style scoped>
.page {
  position: fixed;
  inset: 0;
  padding: 32px 24px;
  overflow: auto;
  background:
    radial-gradient(circle at 20% 10%, rgba(255, 105, 0, 0.04) 0%, transparent 40%),
    radial-gradient(circle at 80% 90%, rgba(255, 105, 0, 0.04) 0%, transparent 40%);
}
.container {
  width: 100%;
  max-width: 1120px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.header h2 {
  font-size: 22px;
  color: #1d1d1f;
}
.btn.ghost {
  background: #fff;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  padding: 8px 12px;
  cursor: pointer;
}
.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}
.card {
  background: #fff;
  border: 1px solid rgba(0, 0, 0, 0.06);
  border-radius: 16px;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.elevated {
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.06);
}
.row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.kv {
  display: grid;
  grid-template-columns: 120px 1fr;
  gap: 8px;
  align-items: center;
}
.kv span {
  color: var(--muted-text);
}
.section-title {
  font-size: 16px;
  margin-bottom: 8px;
}
.loading-text,
.error-text {
  text-align: center;
  padding: 40px;
  color: #999;
  font-size: 14px;
}
.actions {
  display: flex;
  justify-content: center;
  gap: 12px;
  padding-top: 16px;
}
.btn.danger {
  background: var(--color-danger);
  color: #fff;
  border: none;
  padding: 12px 32px;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 600;
  font-size: 15px;
}
.btn.danger:hover {
  opacity: 0.9;
}
</style>
